import { ApiHideProperty, ApiProperty } from '@nestjs/swagger'
import { Column, Entity, JoinTable, ManyToMany, Relation } from 'typeorm'

import { CompleteEntity } from '~/common/entity/common.entity'
import { CommonStatus, DataScope, RoleType } from '~/enums'

import { MenuEntity } from '../menu/menu.entity'
import { UserEntity } from '../user/user.entity'

@Entity({ name: 'system_role' })
export class RoleEntity extends CompleteEntity {
  @Column({ length: 30, unique: true, comment: '角色名称' })
  @ApiProperty({ description: '角色名称' })
  name: string

  @Column({ length: 100, unique: true, comment: '角色权限字符串' })
  @ApiProperty({ description: '角色权限字符串' })
  code: string

  @Column({ comment: '显示顺序' })
  @ApiProperty({ description: '显示顺序' })
  sort: number

  @Column({ name: 'data_scope', type: 'tinyint', default: DataScope.ALL, comment: '数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限）' })
  @ApiProperty({ description: '数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限）', enum: DataScope })
  dataScope: DataScope

  @Column({ name: 'data_scope_dept_ids', length: 500, default: '', comment: '数据范围(指定部门数组)' })
  @ApiProperty({ description: '数据范围(指定部门数组)' })
  dataScopeDeptIds: string

  @Column({ type: 'tinyint', comment: '角色状态（0正常 1停用）' })
  @ApiProperty({ description: '角色状态（0正常 1停用）', enum: CommonStatus })
  status: CommonStatus

  @Column({ type: 'tinyint', default: RoleType.BUILT_IN, comment: '角色类型' })
  @ApiProperty({ description: '角色类型', enum: RoleType })
  type: RoleType

  @Column({ length: 500, nullable: true, comment: '备注' })
  @ApiProperty({ description: '备注' })
  remark: string

  @ApiHideProperty()
  @ManyToMany(() => UserEntity, user => user.roles)
  users: Relation<UserEntity[]>

  @ApiHideProperty()
  @ManyToMany(() => MenuEntity, menu => menu.roles, {})
  @JoinTable({
    name: 'system_role_menus',
    joinColumn: { name: 'role_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'menu_id', referencedColumnName: 'id' },
  })
  menus: Relation<MenuEntity[]>
}
